import { isDate, isPlainObject } from './util'

/**
 * 对 URL 参数编码
 * @param text 字符串
 */
function encode(text: string) {
  return encodeURIComponent(text).replace(/%(40|3A|24|2C|20|5B|5D)/gi, sub => {
    return sub === '%20' ? '+' : decodeURIComponent(sub)
  })
}

/**
 * 生成 URL
 * @param url url
 * @param params 参数
 */
export function buildURL(url: string, params?: any): string {
  if (!params) {
    return url
  }

  const parts: string[] = []

  Object.keys(params).forEach(key => {
    const val = params[key]
    if (val === null || val === void 0) {
      return
    }
    if (typeof val === 'string' && !val.trim()) {
      return
    }

    let values = []
    if (Array.isArray(val)) {
      values = val
      key += '[]'
    } else {
      values = [val]
    }

    values.forEach(val => {
      if (isDate(val)) {
        val = val.toISOString()
      } else if (isPlainObject(val)) {
        val = JSON.stringify(val)
      }
      parts.push(`${encode(key)}=${encode(val)}`)
    })
  })

  const serializedParams = parts.join('&') // 序列化后的参数

  if (serializedParams) {
    // 判断 url 种是否有 hash
    const markIndex = url.indexOf('#')
    if (markIndex !== -1) {
      url = url.slice(0, markIndex)
    }

    url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams
  }

  return url
}
